package com.db.service.impl;

import com.db.Dao.UserDao;
import com.db.Dao.impl.UserDaoImpl;
import com.db.entity.User;
import com.db.service.UserService;
import com.db.util.DButils;

import java.sql.Connection;
import java.sql.SQLException;

public class UserServiceImpl implements UserService {
    @Override
    public User login(User user) {
        Connection conn = null;
        User user1 = null;

        try {

            conn = DButils.getConnection();

            conn.setAutoCommit(false);

            UserDao ud = new UserDaoImpl();
            user1 = ud.login(user);


            conn.commit();

        } catch (Exception e) {
            e.printStackTrace();
            if(conn != null){
                try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); }
            }
            throw new RuntimeException(e);

        }finally{
            DButils.close(conn,null,null);
        }
        return user1;
    }


    @Override
    public Boolean register(User user) {
        Connection conn = null;
        Boolean b = true;
        try{
            conn = DButils.getConnection();
            conn.setAutoCommit(false);
            UserDao ud = new UserDaoImpl();
            User user1 = ud.selectUserByUsername(user);
            if(user1 != null){
                b=false;
            }else{

                ud.insertUser(user);
            }

            conn.commit();
        }catch(Exception e){
            e.printStackTrace();
            if( conn != null ){
                try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); }
            }
            throw new RuntimeException(e);

        }finally{
            DButils.close(conn,null,null);
        }
        return b;
    }
}
